from redis import StrictRedis


class MSRedis(object):
    '''读写分离客户端（只针对程序中用到的命令）'''

    def __init__(self):
        self.master = StrictRedis(host='10.211.55.15', port='6379', db=0)
        self.slave = StrictRedis(host='10.211.55.15', port='6378', db=0)
        self.read_commands = [
            'ttl', 'exist', 'expire', 'get', 'keys',
            'hget', 'hgetall', 'hkeys', 'hmget',
            'sismember', 'smembers', 'sdiff', 'sinter', 'sunion',
            'zrevrange', 'zrevrangebyscore', 'zrevrank', 'zscore'
        ]

    def __getattribute__(self, name):
        if name in ['master', 'slave', 'read_commands']:
            return object.__getattribute__(self, name)
        elif name in self.read_commands:
            print('选择了从库')
            return self.slave.__getattribute__(name)  #  =>  self.slave.get()
        else:
            print('选择了主库')
            return self.master.__getattribute__(name)  # =>  self.master.set()



rds = MSRedis()

res = rds.set('name', 'zhangsan')
print(res)

